package network.themis.rms.console.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author oxchains
 * @time 2018-07-26 13:53
 * @name ShiroAuthRealm
 * @desc:
 */
@Slf4j
public class ShiroAuthRealm extends AuthorizingRealm{

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String usersign = String.valueOf(principals.getPrimaryPrincipal());
        //UserInfo userInfo = (UserInfo) principals.getPrimaryPrincipal();
        try{
            //加入角色权限
            /*final User user=userService.selectByUsername(username);
            final List<Role> roleInfos = roleService.selectRolesByUserId(user.getSid());
            for (Role role : roleInfos) {
                // 添加角色
                authorizationInfo.addRole(role.getRoleSign());
                final List<Permission> permissions = permissionService.selectPermissionsByRoleId(role.getSid());
                for (Permission permission : permissions) {
                    // 添加权限
                    authorizationInfo.addStringPermission(permission.getPermissionSign());
                }
            }*/
        }catch (Exception e){
            log.error("", e);
        }
        return authorizationInfo;
    }

    /**
     * 登录身份认证 username/password
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String usersign = String.valueOf(token.getPrincipal());
        String password = new String((char[]) token.getCredentials());
        // 通过数据库进行验证
        /*final User authentication = userService.authentication(new User(username, password));
        if (authentication == null) {
            throw new AuthenticationException("用户名或密码错误.");
        }*/
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(usersign, password, getName());
        return authenticationInfo;

    }
}
